<?php
namespace Core\Common\Helper;

use Core\Common\Base\Log;
use Core\Common\Route\Request;
use Illuminate\Support\Arr;

/**
 * 错误
 * Class ErrorPack
 * @package App\Helper
 */
class ErrorPack
{
    /**
     * @var int
     */
    public $code;

    /**
     * @var string
     */
    public $msg;

    /**
     * Error constructor.
     * @param string $message
     * @param int $code
     */
    public function __construct($message, $code)
    {
        $this->msg = $message;
        $this->code = $code;
    }

    /**
     * @param string $message
     * @param int $code
     * @return $this
     */
    public static function make($message, $code = 10000)
    {
        return new ErrorPack($message, $code);
    }

    /**
     * 将错误信息输出到日志
     * @param int $level
     * @param array $detail
     * @param \Exception $exception
     */
    public function log($level, $detail=null, $exception=null)
    {
        if (is_null($detail)) {
            $detail = [];
        }

        if (!is_null($exception)) {
            $detail = $detail + [
                'exception' => $exception->getMessage(),
                'backtrace' => array_slice($exception->getTrace(), 0, 3),
                'file' => $exception->getFile(),
                'line' => $exception->getLine()
            ];
        }

        $context = [
            'userid' => Arr::get(Request::request(), 'user_id'),
            'message' => $this->msg,
            'code' => $this->code,
            'detail' => $detail
        ];

        if ($level <= LOG_NOTICE) {
            Log::apperror($level, $context);
        } else {
            Log::info($level, $context);
        }
    }
}